package com.java.service;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.java.common.ProductFileService;
import com.java.control.search.ConditionPart;
import com.java.control.search.SearchCond;
import com.java.entity.Product;
import com.java.entity.SupplierQuotation;

/**
 * 产品管理服务
 * @author wqf
 * @version  Nov 24, 2011 11:51:06 AM
 */
@Transactional(propagation = Propagation.REQUIRED,readOnly=false, rollbackFor = Exception.class)
public class ProductService extends BaseService{

	/**
	 * 添加产品
	 * @param role
	 */
	public void addProduct(Product product){
		this.dao.saveObject(product);
	}
	
	/**
	 * 编辑产品（for dwr）
	 * @param product
	 */
	public void editProduct(Product product){
		if(null == product.getId()){
			this.addProduct(product);
		}else{
			this.updateProduct(product);
		}
	}	
	
	/**
	 * 修改产品
	 * @param product
	 */
	public void updateProduct(Product product){
		this.dao.updateObject(product);
	}
	
	/**
	 * 删除产品，同时删除报价
	 * @param id
	 */
	public void deleteProduct(Long id){
		Product product = this.dao.loadObject(Product.class, id);
		if(product!=null){
			List<SupplierQuotation> list = this.dao.loadObjects(SupplierQuotation.class, "product.id=?", null, null, null, product.getId());
			for(SupplierQuotation entity:list){
				this.dao.deleteObject(entity);
			}
			this.dao.deleteObject(product);			
		}
	}

	public void deleteProductByIds(String ids){
		if(StringUtils.isNotBlank(ids)){
			String []id  = ids.split(",");
			for(String s:id){
				deleteProduct(Long.parseLong(s));
			}			
		}	
	}
	
	public Product getProductById(Long id){
		return this.dao.loadObject(Product.class, id);
	}
	
	public List<Product> getProductByIds(String ids){
		if(StringUtils.isNotBlank(ids)){
			return this.dao.loadObjects(Product.class, "id in(" + ids + ")", "id desc", null, null);			
		}
		return null;
	}
	
	/**
	 * 删除图片
	 * @param id
	 */
	public void deleteImage(Long id){
		Product product = this.dao.loadObject(Product.class, id);
		if(null != product && StringUtils.isNotBlank(product.getImageUri())){
			try {				
				ProductFileService.Product.delete(product.getImageUri());				
			} catch (FileNotFoundException ex) {
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			product.setImageUri("");
			this.dao.updateObject(product);
		}
	}
	
	public List<Product> getProductList(SearchCond searchCond){
		ConditionPart condPart = searchCond.getCondition();
		Object params[]=condPart.getParams().toArray(new Object[0]);
		return this.dao.loadObjects(Product.class,condPart.getExpression(), "id", searchCond.getPageSize(), searchCond.getPageIndex(), params);		
	}
	
}
